<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search as IconSearch, Plus as IconPlus, View as IconView, Edit as IconEdit, Delete as IconDelete } from '@element-plus/icons-vue'
import itemApi from '@/api/item'
import categoryApi from '@/api/category'
import type { ItemInfo, ItemListParams, CreateItemParams, UpdateItemParams } from '@/api/item'
import type { CategoryInfo } from '@/api/category'

const tableData = ref<ItemInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchItemName = ref('')
const searchCategoryId = ref<number | null>(null)
const loading = ref(false)
const categoryOptions = ref<CategoryInfo[]>([])

// 创建物品相关数据
const createDialogVisible = ref(false)
const createFormRef = ref()
const createForm = ref<CreateItemParams>({
  itemName: '',
  categoryId: undefined as any,
  specification: '',
  unit: '',
  minimumStock: 0,
  maximumStock: 0,
})

// 编辑物品相关数据
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = ref<UpdateItemParams>({
  itemName: '',
  categoryId: undefined,
  specification: '',
  unit: '',
  minimumStock: undefined,
  maximumStock: undefined,
})
const editingItemId = ref<number | null>(null)

// 查看物品详情相关数据
const detailDialogVisible = ref(false)
const itemDetail = ref<ItemInfo | null>(null)
const detailLoading = ref(false)

// 表单验证规则 (创建和编辑共用部分)
const itemFormRules = {
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  specification: [
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ],
  unit: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  minimumStock: [
    { required: true, message: '请输入最小库存', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
           callback(new Error('请输入最小库存'))
        } else if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效的数字'))
        } else if (value < 0) {
          callback(new Error('不能小于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  maximumStock: [
    { required: true, message: '请输入最大库存', trigger: 'blur' },
    {
       validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
           callback(new Error('请输入最大库存'))
        } else if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效的数字'))
        } else if (value < 0) {
          callback(new Error('不能小于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取物品列表
const getItemList = async () => {
  loading.value = true
  try {
    const params: ItemListParams = {
      page: currentPage.value,
      pageSize: pageSize.value,
      itemName: searchItemName.value.trim() || undefined,
      categoryId: searchCategoryId.value || undefined
    }
    const res = await itemApi.getItemList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取物品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类选项
const getCategoryOptions = async () => {
  try {
    // 获取所有分类作为选项
    const res = await categoryApi.getCategoryList({ page: 1, pageSize: 1000 })
    // 为了方便选择，将树形结构拍平或者处理成 cascader 适用的格式
    // 这里简单处理，直接使用列表，如果分类层级较多，可能需要更复杂的处理
    categoryOptions.value = res.data.list
  } catch (error) {
    // 分类获取失败不影响主流程
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getItemList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getItemList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getItemList()
}

// 打开创建物品对话框
const handleCreate = () => {
  createDialogVisible.value = true
  createForm.value = {
    itemName: '',
    categoryId: undefined as any,
    specification: '',
    unit: '',
    minimumStock: 0,
    maximumStock: 0,
  }
}

// 提交创建物品表单
const handleSubmit = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await itemApi.createItem(createForm.value)
        ElMessage.success('创建物品成功')
        createDialogVisible.value = false
        getItemList() // 刷新列表
      } catch (error) {
        ElMessage.error('创建物品失败')
      }
    }
  })
}

// 取消创建
const handleCancel = () => {
  createDialogVisible.value = false
  createFormRef.value?.resetFields()
}

// 查看物品详情
const handleViewDetail = async (item: ItemInfo) => {
  detailLoading.value = true
  try {
    const res = await itemApi.getItemById(item.itemId)
    itemDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取物品详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  itemDetail.value = null
}

// 打开编辑物品对话框
const handleEdit = async (item: ItemInfo) => {
  try {
    const res = await itemApi.getItemById(item.itemId)
    const data = res.data
    editForm.value = {
      itemName: data.itemName,
      categoryId: data.categoryId,
      specification: data.specification,
      unit: data.unit,
      minimumStock: data.minimumStock,
      maximumStock: data.maximumStock,
    }
    editingItemId.value = item.itemId
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取物品信息失败')
  }
}

// 提交编辑物品表单
const handleEditSubmit = async () => {
  if (!editFormRef.value || !editingItemId.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await itemApi.updateItem(editingItemId.value!, editForm.value)
        ElMessage.success('更新物品成功')
        editDialogVisible.value = false
        getItemList() // 刷新列表
      } catch (error) {
        ElMessage.error('更新物品失败')
      }
    }
  })
}

// 取消编辑
const handleEditCancel = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
  editingItemId.value = null
}

// 删除物品
const handleDelete = async (item: ItemInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除物品"${item.itemName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 用户确认删除后，调用 API
    itemApi.deleteItem(item.itemId)
      .then(() => {
        ElMessage.success('删除物品成功');
        getItemList(); // 刷新列表
      })
      .catch((error: any) => {
        // 检查是否是外键约束错误
        let isForeignKeyError = false;
        let displayMessage = '删除物品失败';

        if (error.response && error.response.data) {
          const errorDataString = JSON.stringify(error.response.data).toLowerCase();
          if (errorDataString.includes('foreign key constraint fails') && errorDataString.includes('inbound_records')) {
            isForeignKeyError = true;
            displayMessage = '该物品已被入库记录引用，无法直接删除。请先处理相关入库记录。';
          } else if (error.response.data.message) {
            displayMessage = error.response.data.message;
          }
        } else if (error.message) {
           displayMessage = error.message;
        }

        if (isForeignKeyError) {
          ElMessage.warning(displayMessage);
        } else {
          ElMessage.error(displayMessage);
        }
      });

  } catch (error: any) {
    // 处理用户取消删除或其他确认框错误
    if (error !== 'cancel') {
      ElMessage.error('删除操作异常');
    }
  }
};

onMounted(() => {
  getCategoryOptions()
  getItemList()
})
</script>

<template>
  <div class="item-list-container">
    <div class="search-bar">
      <el-input
        v-model="searchItemName"
        placeholder="请输入物品名称"
        class="search-input"
        :prefix-icon="IconSearch"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchCategoryId"
        placeholder="请选择分类"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="cat in categoryOptions"
          :key="cat.categoryId"
          :label="cat.categoryName"
          :value="cat.categoryId"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" :icon="IconPlus" @click="handleCreate">创建物品</el-button>
    </div>

    <el-table :data="tableData" border v-loading="loading" style="width: 100%" class="item-table">
      <el-table-column prop="itemId" label="物品ID" width="100" />
      <el-table-column prop="itemName" label="物品名称" width="180" />
      <el-table-column prop="category.categoryName" label="分类" width="120">
        <template #default="{ row }">
          {{ row.category?.categoryName || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="specification" label="规格" width="160" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="minimumStock" label="最小库存" width="100" />
      <el-table-column prop="maximumStock" label="最大库存" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <div class="action-btns">
            <el-button
              type="primary"
              :icon="IconView"
              circle
              @click="handleViewDetail(row)"
            />
            <el-button
              type="warning"
              :icon="IconEdit"
              circle
              @click="handleEdit(row)"
            />
            <el-button
              type="danger"
              :icon="IconDelete"
              circle
              @click="handleDelete(row)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>
  </div>

  <!-- 创建物品对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="创建物品"
    width="500px"
    @close="handleCancel"
  >
    <el-form
      ref="createFormRef"
      :model="createForm"
      :rules="itemFormRules"
      label-width="100px"
    >
      <el-form-item label="物品名称" prop="itemName">
        <el-input v-model="createForm.itemName" placeholder="请输入物品名称" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="createForm.categoryId" placeholder="请选择分类">
          <el-option
            v-for="cat in categoryOptions"
            :key="cat.categoryId"
            :label="cat.categoryName"
            :value="cat.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input v-model="createForm.specification" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="createForm.unit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="最小库存" prop="minimumStock">
        <el-input-number
          v-model="createForm.minimumStock"
          :min="0"
          :controls="false"
          placeholder="请输入最小库存"
        />
      </el-form-item>
      <el-form-item label="最大库存" prop="maximumStock">
        <el-input-number
          v-model="createForm.maximumStock"
          :min="0"
          :controls="false"
          placeholder="请输入最大库存"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑物品对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑物品"
    width="500px"
    @close="handleEditCancel"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="itemFormRules"
      label-width="100px"
    >
      <el-form-item label="物品名称" prop="itemName">
        <el-input v-model="editForm.itemName" placeholder="请输入物品名称" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="editForm.categoryId" placeholder="请选择分类">
          <el-option
            v-for="cat in categoryOptions"
            :key="cat.categoryId"
            :label="cat.categoryName"
            :value="cat.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input v-model="editForm.specification" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="editForm.unit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="最小库存" prop="minimumStock">
        <el-input-number
          v-model="editForm.minimumStock"
          :min="0"
          :controls="false"
          placeholder="请输入最小库存"
        />
      </el-form-item>
      <el-form-item label="最大库存" prop="maximumStock">
        <el-input-number
          v-model="editForm.maximumStock"
          :min="0"
          :controls="false"
          placeholder="请输入最大库存"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleEditCancel">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 物品详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="物品详情"
    width="600px"
    @close="handleCloseDetail"
  >
    <div v-loading="detailLoading">
      <template v-if="itemDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="物品ID">
            {{ itemDetail.itemId }}
          </el-descriptions-item>
          <el-descriptions-item label="物品名称">
            {{ itemDetail.itemName }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            {{ itemDetail.category?.categoryName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="规格">
            {{ itemDetail.specification }}
          </el-descriptions-item>
          <el-descriptions-item label="单位">
            {{ itemDetail.unit }}
          </el-descriptions-item>
          <el-descriptions-item label="最小库存">
            {{ itemDetail.minimumStock }}
          </el-descriptions-item>
          <el-descriptions-item label="最大库存">
            {{ itemDetail.maximumStock }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ itemDetail.createdAt }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ itemDetail.updatedAt }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </div>
  </el-dialog>

</template>

<style scoped>
.item-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.item-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.action-btns {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-button.is-circle {
  padding: 6px;
}

.search-select {
  width: 180px;
}

.el-select {
  width: 100%;
}

.el-input-number {
  width: 100%;
}

</style> 